//
//  ViewController.m
//  解析HTML
//
//  Created by 尚往文化 on 17/9/13.
//  Copyright © 2017年 YBing. All rights reserved.
//

#import "YBNewsController.h"
#import <TFHpple.h>
#import "YBNews.h"
#import "YBNewsCell.h"
#import <MJRefresh.h>
#import "YBNewsDetailController.h"

@interface YBNewsController ()

@property (nonatomic, strong) NSMutableArray<YBNews *> *datas;

@property (nonatomic, assign) NSInteger page;


@end

@implementation YBNewsController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTableView];
    
}

- (void)setupTableView
{
    [self.tableView registerNib:[UINib nibWithNibName:@"YBNewsCell" bundle:nil] forCellReuseIdentifier:@"YBNewsCell"];
    self.tableView.estimatedRowHeight = UITableViewAutomaticDimension;
    self.tableView.rowHeight = 100;
    YBWeakSelf
    kSetupRefreshNormalHeader
}

- (void)loadData
{
    [super loadData];
    
    NSString *url = [NSString stringWithFormat:@"%@1.html", self.url];
    [YBHttpTool get:url cacheType:YBCacheTypeReturnCacheDataThenLoad success:^(TFHpple *doc) {
        [self.tableView.mj_header endRefreshing];
        NSMutableArray *datas = [self parseWithHpple:doc];
        self.datas = datas;
        YBWeakSelf
        if (self.tableView.mj_footer==nil) {
            self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                [weakSelf loadMoreData];
            }];
        }
        if (datas.count==0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer resetNoMoreData];
        }
        self.page = 2;
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
    }];
    
}

- (void)loadMoreData
{
    NSString *url = [NSString stringWithFormat:@"%@%zi.html", self.url, self.page];
    
    [YBHttpTool get:url success:^(TFHpple *doc) {
        [self.tableView.mj_footer endRefreshing];
        NSArray *datas = [self parseWithHpple:doc];
        [self.datas addObjectsFromArray:datas];
        
        if (datas.count==0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            self.page++;
            [self.tableView.mj_footer resetNoMoreData];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
    }];
    
    
}

- (NSMutableArray<YBNews *> *)parseWithHpple:(TFHpple *)doc
{
    NSArray<TFHppleElement *> *elements  = [doc searchWithXPathQuery:@"//ul[@id='list_holder']"];
    TFHppleElement *listElement = [elements firstObject];
    NSArray<TFHppleElement *> *list = [listElement childrenWithTagName:@"li"];
    NSMutableArray *datas = [NSMutableArray array];
    [list enumerateObjectsUsingBlock:^(TFHppleElement * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        TFHppleElement *titleElement = [obj firstChildWithClassName:@"clearfix newstitle"];
        TFHppleElement *aElement = [titleElement firstChildWithTagName:@"a"];
        NSString *href = [aElement objectForKey:@"href"];
        NSString *title = aElement.text;
        
        TFHppleElement *descElement = [[obj childrenWithClassName:@"clearfix"] lastObject];
        aElement = [descElement firstChildWithTagName:@"a"];
        TFHppleElement *imgElement = [aElement firstChildWithTagName:@"img"];
        NSString *imgUrl = [imgElement objectForKey:@"src"];
        
        TFHppleElement *descElement2 = [descElement firstChildWithClassName:@"newsinfor"];
        NSString *desc = descElement2.text;
        
        TFHppleElement *tagElement = [descElement firstChildWithClassName:@"clearfix zx_manage"];
        TFHppleElement *float_lElement = [tagElement firstChildWithClassName:@"float-l"];
        NSArray<TFHppleElement *> *arr = [float_lElement childrenWithTagName:@"span"];
        __block NSString *timeStr = nil;
        __block NSString *category = nil;
        __block NSString *source = nil;
        [arr enumerateObjectsUsingBlock:^(TFHppleElement * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx==0) {
                timeStr = obj.text;
            } else if (idx==1) {
                category = obj.text;
            } else {
                source = obj.text;
            }
        }];
        
        TFHppleElement *float_rElement = [tagElement firstChildWithClassName:@"float-r"];
        TFHppleElement *likenumElement = [[float_rElement childrenWithTagName:@"text"] lastObject];
        NSString *likenum = likenumElement.content;
        
        YBNews *news = [YBNews newsWithTitle:title desc:desc url:href img:imgUrl time:timeStr category:category source:source likenum:likenum];
        [datas addObject:news];
    }];
    return datas;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YBNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YBNewsCell" forIndexPath:indexPath];
    cell.news = self.datas[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    YBNewsDetailController *vc = [YBNewsDetailController new];
    
    NSString *host = [self.url stringByDeletingLastPathComponent];
    NSString *lastPath = self.datas[indexPath.row].url;
    
    vc.url = [NSString stringWithFormat:@"%@%@", @"http://www.cocoachina.com/", lastPath];
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 9;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 9;
}


@end
